import React, {
    Component
} from "react";
import OmsSelect from '../../../../components/display/omsSelect';
import {
    versionType,
    refresh
} from './selectData';
import {
    Form,
    Input,
    Row,
    Col,
    Button,
    DatePicker,
    Switch,
    message,
    Radio,
    Select
} from 'antd';
import SaasModal from '../../../../components/display/SaasModal';
import {
    EVCSConfDetails,
    EVCSConfAdd
} from '../../../../fetch/fetchApi';
import moment from 'moment';

const {
    RangePicker
} = DatePicker;
const FormItem = Form.Item;
const createForm = Form.create;
const RadioGroup = Radio.Group;
const Option = Select.Option;
// const {TextArea} = Input;

class Configuration extends Component {
    constructor(props) {
        super(props);
        this.state = {
            refresh: 0,
            DetailInfo: {
                inSecret: {},
                outSecret: {}
            },
            display: true
        };
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.visible && nextProps.selectInfo.appkey && nextProps.hasGetApi) {
            console.log('nextProps.selectInfo.appke', nextProps.selectInfo.appkey);
            EVCSConfDetails({
                appkey: nextProps.selectInfo.appkey
            }).then(response => {
                if (response && response.data && response.data.code === "200" && response.data.data) {
                    let res = response.data;
                    this.props.alreadyGet();
                    this.setState({
                        DetailInfo: res.data,
                        isShowDelayInput: res.data.stubStatusRefreshInterval > 0 ? true : false
                    })
                } else {
                    this.setState({
                        DetailInfo: {
                            appkey: nextProps.selectInfo.appkey,
                            inSecret: {},
                            outSecret: {},
                        }
                    })
                }
            })
            this.setState({
                display: true
            })
        }
    }
    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!!err) {
                return;
            }
            console.log(values);
            const dateFormat = 'YYYY.MM.DD HH:mm:ss';
            values.enableSecurity = values.enableSecurity ? 1 : 0;
            values.enableStartDate = values.enableDate[0].format(dateFormat);
            values.enableEndDate = values.enableDate[1].format(dateFormat);
            // 大于0表示延时发送，取时间参数
            if (values.stubStatusRefreshInterval > 0) {
                values.stubStatusRefreshInterval = values.delayTime;
            }
            delete values.enableDate;
            EVCSConfAdd(values).then(response => {
                console.log('response', response);
                if (response && response.data && response.data.code === "200") {
                    // let res=response.data
                    this.props.handleCancel();
                    message.success('新增成功');
                }
            })
        });
    };

    validateKey = (rule, value, callback) => {
        if (value && value.length > 18) {
            callback('请输入正确的社会信用代码');
        } else {
            callback();
        }
    }

    validateMail = (rule, value, callback) => {
        let myreg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        if (value && !myreg.test(value)) {
            callback('请输入正确的邮箱');
        } else {
            callback();
        }
    };

    validatePhone = (rule, value, callback) => {
        let myreg = /^1[3|4|5|7|8|9][0-9]{9}$/;
        if (value && !myreg.test(value)) {
            callback('请输入正确的手机号');
        } else {
            callback();
        }
    };
    // endTimeLess = (rule, value, callback) => {
    //     let startTime;
    //     let endTime;
    //     let differDay;
    //     if (value && value.length > 0) {
    //         startTime = value[0].format('x');
    //         endTime = value[1].format('x');
    //         differDay = ((endTime - startTime) / 1000 / 60 / 60 / 24);
    //     }
    //     if (differDay > 7) {
    //         callback('相距不能超过7天');
    //     } else {
    //         callback();
    //     }
    // }

    handleConfTypeChange = (e) => {
        this.props.form.resetFields();
        EVCSConfDetails({
            appkey: this.props.selectInfo.appkey,
            configType: (e.target.value ? e.target.value : null)
        }).then(response => {
            if (response && response.data && response.data.code === "200" && response.data.data) {
                let res = response.data;
                this.props.alreadyGet();
                this.setState({
                    DetailInfo: res.data,
                })
            } else {
                this.setState({
                    DetailInfo: {
                        appkey: this.props.selectInfo.appkey,
                        inSecret: {},
                        outSecret: {},
                    }
                })
            }
        })
        this.setState({
            display: !this.state.display
        })
    }

    handlePushMethodChange = (e) => {
        this.setState({
            isShowDelayInput: e === 1 ? true : false
        })
    }

    render() {
        const {
            getFieldDecorator
        } = this.props.form;
        const wrapper = {
            xl: 18
        };
        const config = {
            rules: [{
                required: true,
                message: "该项为必填项"
            }]
        };
        const formItemLayout = {
            labelCol: {
                xl: {
                    span: 4
                },
                sm: {
                    span: 8
                },
            },
            wrapperCol: {
                xl: {
                    span: 20
                },
                sm: {
                    span: 16
                },
            },
        };
        const tailFormItemLayout = {
            wrapperCol: {
                xl: {
                    span: 20,
                    offset: 4,
                },
            },
        };
        const statusList = [{
            id: "0",
            name: "关闭"
        }, {
            id: "1",
            name: "开启"
        }]
        const dateFormat = 'YYYY.MM.DD HH:mm:ss';
        return (
            <SaasModal visible={this.props.visible} handleCancel={this.props.handleCancel} title={'配置信息'}>
                <form form={this.props.form}>
                    <Row gutter={4}>
                        <Col {...wrapper}>
                            <FormItem
                            label="APPKEY"
                            {...formItemLayout}
                            >
                                {getFieldDecorator('appkey',{
                                    rules: [
                                        {
                                            required: true,
                                            message: "该项为必填项"
                                        },
                                        { validator: this.validateKey}
                                    ],
                                    initialValue:this.state.DetailInfo.appkey
                                })(
                                    <Input placeholder={'统一社会信用代码'} disabled={Boolean(this.state.DetailInfo.appkey)}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col {...wrapper}>
                            <FormItem
                            label="配置类型"
                            {...formItemLayout}
                            >
                                {getFieldDecorator('configType',{...{initialValue:this.state.DetailInfo.configType}})(
                                    <RadioGroup initialValue={0} onChange={this.handleConfTypeChange}>
                                        <Radio value={0}>evcs</Radio>
                                        <Radio value={1}>dxp</Radio>
                                    </RadioGroup>
                                )}
                            </FormItem>
                        </Col>
                        <Col {...wrapper}>
                            <FormItem
                            label="IP   授权"
                            {...formItemLayout}
                            >
                                {getFieldDecorator('ipList',{...config,...{initialValue:this.state.DetailInfo.ipList}})(
                                    <Input placeholder={'请输入授权IP，用“，”号隔开'}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col {...wrapper}>
                            <FormItem
                            label="互联互通"
                            {...formItemLayout}
                            >
                                {getFieldDecorator('status',{...config,...{initialValue:this.state.DetailInfo.status!==undefined&&this.state.DetailInfo.status!==null?this.state.DetailInfo.status.toString():undefined}})(
                                    <OmsSelect data={statusList}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col {...wrapper}>
                            <FormItem
                            {...formItemLayout}
                            label="服  务 器"
                            >
                                {getFieldDecorator('serverUrl',{...config,...{initialValue:this.state.DetailInfo.serverUrl}})(
                                    <Input placeholder={'请输入第三方服务器地址'}/>
                                )}
                            </FormItem>
                        </Col>
                        {this.state.display&&<Col {...wrapper}>
                            <FormItem
                            {...formItemLayout}
                            label="版 本"
                            >
                                {getFieldDecorator('version',{rules: [{ required: this.state.display, message: '该项为必填项' }],...{initialValue:this.state.DetailInfo.version!==undefined&&this.state.DetailInfo.version!==null?this.state.DetailInfo.version.toString():undefined}})(
                                   /*<OmsSelect data={versionType}/>*/
                                   <Select initialValue="starcharge星充扩展版">
                                        <Option value="starcharge星充扩展版">starcharge星充扩展版</Option>
                                        <Option value="V20160701">V20160701标准2016版</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>}
                        <Col {...wrapper}>
                            <FormItem
                            {...formItemLayout}
                            label="刷新间隔"
                            >
                                <Row gutter={8}>
                                    <Col span={12}>
                                        {getFieldDecorator('stubStatusRefreshInterval',{...config,...{
                                            initialValue:this.state.DetailInfo.stubStatusRefreshInterval>0?1:this.state.DetailInfo.stubStatusRefreshInterval
                                        }})(
                                            /*<OmsSelect data={refresh}/>*/
                                            <Select initialValue={-1} onChange={this.handlePushMethodChange}>
                                                <Option value={-1}>不推送</Option>
                                                <Option value={0}>实时推送</Option>
                                                <Option value={1}>延时推送</Option>
                                            </Select>
                                            
                                        )}
                                    </Col>
                                    <Col span={12}>
                                        {this.state.isShowDelayInput&&
                                            getFieldDecorator('delayTime',{
                                                initialValue:this.state.DetailInfo.stubStatusRefreshInterval>0?this.state.DetailInfo.stubStatusRefreshInterval:""
                                            })(
                                                <Input placeholder="请输入延时时间(分钟)"/>
                                            )
                                        }
                                    </Col>
                                </Row>
                            </FormItem>
                        </Col>
                        {!this.state.display&&<Col {...wrapper}>
                            <FormItem
                            {...formItemLayout}
                            label="上报级别"
                            >
                                {getFieldDecorator('level',{rules: [{ required: !this.state.display, message: '该项为必填项' }],...{initialValue:this.state.DetailInfo.level}})(
                                    <Select initialValue={0}>
                                        <Option value={0}>0级</Option>
                                        <Option value={1}>1级</Option>
                                        <Option value={2}>2级</Option>
                                        <Option value={3}>3级</Option>
                                        <Option value={4}>4级</Option>
                                        <Option value={5}>5级</Option>
                                        <Option value={6}>6级</Option>
                                        <Option value={7}>7级</Option>
                                        <Option value={8}>8级</Option>
                                        <Option value={9}>9级</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>}
                        <Col {...wrapper}>
                            <FormItem
                            {...formItemLayout}
                            label="有效时间"
                            >
                                {getFieldDecorator('enableDate',{
                                    rules: [
                                        {
                                            required: true,
                                            message: "该项为必填项"
                                        },
                                    ],
                                    initialValue:this.state.DetailInfo.enableStartDate?[moment(this.state.DetailInfo.enableStartDate, dateFormat), moment(this.state.DetailInfo.enableEndDate, dateFormat)]:undefined,
                                })(
                                    <RangePicker
                                    format={dateFormat}
                                  />
                                )}
                            </FormItem>
                        </Col>
                        <Col {...wrapper}>
                            <FormItem
                            {...formItemLayout}
                            label="第三方秘钥"
                            >
                                {getFieldDecorator('outAesSecret',{...config,...{initialValue:this.state.DetailInfo.outSecret&&this.state.DetailInfo.outSecret.aesSecret}})(
                                    <Input placeholder={"请输入数据加密秘钥"}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col {...wrapper}>
                            <FormItem
                            {...tailFormItemLayout}
                            >
                                {getFieldDecorator('outSigSecret',{...config,...{initialValue:this.state.DetailInfo.outSecret&&this.state.DetailInfo.outSecret.sigSecret}})(
                                    <Input placeholder={"请输入运营商秘钥"}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col {...wrapper}>
                            <FormItem
                            {...tailFormItemLayout}
                            >
                                {getFieldDecorator('outAesIv',{...config,...{initialValue:this.state.DetailInfo.outSecret&&this.state.DetailInfo.outSecret.aesIv}})(
                                    <Input placeholder={"请输入初始化向量"}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col {...wrapper}>
                            <FormItem
                            {...tailFormItemLayout}
                            >
                                {getFieldDecorator('outOperatorSecret',{...config,...{initialValue:this.state.DetailInfo.outSecret&&this.state.DetailInfo.outSecret.operatorSecret}})(
                                    <Input placeholder={"请输入签名秘钥"}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col {...wrapper}>
                            <FormItem
                            {...formItemLayout}
                            label="星充秘钥"
                            >
                                {getFieldDecorator('inAesSecret',{...config,...{initialValue:this.state.DetailInfo.inSecret&&this.state.DetailInfo.inSecret.aesSecret}})(
                                    <Input placeholder={"请输入数据加密秘钥"}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col {...wrapper}>
                            <FormItem
                            {...tailFormItemLayout}
                            >
                                {getFieldDecorator('inSigSecret',{...config,...{initialValue:this.state.DetailInfo.inSecret&&this.state.DetailInfo.inSecret.sigSecret}})(
                                    <Input placeholder={"请输入运营商秘钥"}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col {...wrapper}>
                            <FormItem
                            {...tailFormItemLayout}
                            >
                                {getFieldDecorator('inAesIv',{...config,...{initialValue:this.state.DetailInfo.inSecret&&this.state.DetailInfo.inSecret.aesIv}})(
                                    <Input placeholder={"请输入初始化向量"}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col {...wrapper}>
                            <FormItem
                            {...tailFormItemLayout}
                            >
                                {getFieldDecorator('inOperatorSecret',{...config,...{initialValue:this.state.DetailInfo.inSecret&&this.state.DetailInfo.inSecret.operatorSecret}})(
                                    <Input placeholder={"请输入签名秘钥"}/>
                                )}
                            </FormItem>
                        </Col>
                        {this.state.display&&<Col {...wrapper}>
                            <FormItem
                            {...formItemLayout}
                            label="签名/token"
                            >
                            {getFieldDecorator('enableSecurity', {valuePropName: 'checked',initialValue: this.state.DetailInfo.enableSecurity==1?true:false})(
                                <Switch />
                            )}
                            </FormItem>
                        </Col>}
                        <Col {...wrapper}>
                            <FormItem
                            {...tailFormItemLayout}
                            >
                                <Button style={{marginRight:4}} type="primary" htmlType="submit" onClick={this.handleSubmit}>{'保存配置'}</Button>
                            </FormItem>
                        </Col>
                    </Row>
                </form>
            </SaasModal>
        )
    }
}
Configuration = createForm()(Configuration);
export default Configuration;